package com.boot.service.impl;

import com.boot.model.WordConfig;
import com.boot.model.WordGenConfig;
import com.boot.service.IWordService;
import com.boot.util.JFreeChartUtil;
import com.boot.util.JdbcTemplatePlus;
import com.boot.util.SpelUtils;
import com.boot.util.TitlesUtils;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONString;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WordServiceImpl implements IWordService {
    @Autowired
    private JdbcTemplatePlus jdbcTemplate;


    String localDir = "/offer/";
    String imgLocalDir = "/jfreechart/";
    @Override
    public void genWord(WordGenConfig wordGenConfig) {
        String value = SpelUtils.getValue(wordGenConfig.getQuerySql(), wordGenConfig);
        Map<String, Object> map = jdbcTemplate.queryForMap(value);
        map.put("localDir", localDir);
        String fileName = SpelUtils.getValue("{#localDir}" + wordGenConfig.getWordNameTemplate(), map);

        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }

        TitlesUtils thisTitle = new TitlesUtils();
        String sqlTemplate = "SELECT * from word_config WHERE version={#version} AND subject_id = {#subjectId}";
        String sql = SpelUtils.getValue(sqlTemplate, new HashMap<String, Object>() {{
            put("version", wordGenConfig.getVersion());
            put("subjectId", wordGenConfig.getSubjectId());
        }});
        List<WordConfig> list = jdbcTemplate.getList(sql, WordConfig.class);
        List<WordConfig> rlist = new LinkedList<>();
        for (WordConfig config : list) {
            String countSql = SpelUtils.getValue(config.getCountSql(), wordGenConfig);
            if (jdbcTemplate.queryForObject(countSql, Integer.class).compareTo(0) != 0) { //确定要显示
                String querySql = SpelUtils.getValue(config.getQuerySql(), wordGenConfig);
                List<Map<String, Object>> maps = jdbcTemplate.queryForList(querySql);
                if (config.getTitleLevel().compareTo(1) == 0) {
                    config.setText(String.format("%s、%s", thisTitle.one(), SpelUtils.getValue(config.getTextTemplate(), maps)));
                    rlist.add(config);
                } else if (config.getTitleLevel().compareTo(2) == 0) {
                    config.setText(String.format("(%s) %s", thisTitle.two(), SpelUtils.getValue(config.getTextTemplate(), maps)));
                    rlist.add(config);
                } else {
                    if (config.getIsTable().equals(0)) { //text
                        if (config.getSplicing().compareTo(1) == 0) {
                            WordConfig wordConfig = rlist.get(rlist.size() - 1);
                            wordConfig.setText(wordConfig.getText() + SpelUtils.getValue(config.getTextTemplate(), maps));
                        } else {
                            config.setText(SpelUtils.getValue(config.getTextTemplate(), maps));
                            rlist.add(config);
                        }
                    } else if (config.getIsTable().equals(2)) { //image
                        XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
                        //获取所有线条
                        Set<String> keys = maps.stream().map(item -> item.get("key") + "").collect(Collectors.toSet());
//                         List<XYSeries> xys = maps.stream().map(item -> new XYSeries(item.get("key") + "")).collect(Collectors.toList());
                        for (String key : keys) {
                            XYSeries series = new XYSeries(key);
                            xySeriesCollection.addSeries(series);
                            for (Map<String, Object> data : maps) {
                                if (key.equals(data.get("key") + "")) {
                                    if ("1".equals(data.get("isLine"))) { //line
//                                    填充数据
                                        series.add(Double.valueOf(data.get("x") + ""), Double.valueOf(data.get("y") + ""));
                                    }else
                                    if ("0".equals(data.get("isLine"))) { //

                                    }
                                }
                            }
                        }
                        JSONObject jsonObject = JSONObject.fromObject(config.getRemark().trim());
                        JFreeChart chart = JFreeChartUtil.createChart(xySeriesCollection, jsonObject.getString("asX"),  jsonObject.getString("asY"), config.getTextTemplate() );
                        String saveAsFile = JFreeChartUtil.saveAsFile(chart, imgLocalDir + System.currentTimeMillis()+"/"+UUID.randomUUID().toString()+".png", 600, 400);
                        config.setImgFile(saveAsFile);
                        rlist.add(config);
                    }
                }
            }
        }

        XWPFDocument document = new XWPFDocument();
        for (int idnex = 0; idnex < rlist.size(); idnex++) {
            WordConfig config = rlist.get(idnex);
            XWPFParagraph paragraph = document.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.valueOf(config.getParagraphAlignment().toUpperCase()));
            paragraph.setIndentationFirstLine(config.getIndentation()); //缩进
            XWPFRun run = paragraph.createRun();
            if (config.getIsTable().equals(2)) { //img
                FileInputStream is = null;
                try {
                    is = new FileInputStream(config.getImgFile());
//                  //     1cm = 28.33
                    run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, config.getImgFile(), Units.toEMU(414.73), Units.toEMU(186.40)); // 100x100 pixels
                    continue;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (InvalidFormatException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }
            run.setBold(config.getBold().equals(1));
            run.setText(config.getText());
            run.setFontSize(config.getFontSize());
            run.setFontFamily(config.getFontFamily());
        }

        //写入
        try {
            FileOutputStream out = new FileOutputStream(file);
            document.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            wordGenConfig.setSuccess(0);
//            jdbcTemplate.update("");
        } finally {
            wordGenConfig.setSuccess(1);
            wordGenConfig.setGenDate(new Date());
            wordGenConfig.setFtpPath(file.getPath());
//            jdbcTemplate.update("");

//            del file
            for (String f : rlist.stream().filter(item -> item.getIsTable().equals(2)).map(item -> item.getImgFile()).collect(Collectors.toList())) {
                File delFile = new File(f).getParentFile();
                if (delFile.isDirectory()) {
                    for (File file1 : delFile.listFiles()) {
                        file1.delete();
                    }
                }
                delFile.delete();
            }
        }
    }
}
